package com.meixiaoliang.portal.modular.system.controller;

import java.io.IOException;
import java.time.LocalDateTime;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meixiaoliang.portal.core.util.AssertUtil;
import com.meixiaoliang.portal.core.util.FileUtil;
import com.meixiaoliang.portal.core.util.ResponseUtil;
import com.meixiaoliang.portal.core.util.UuidUtil;
import com.meixiaoliang.portal.modular.system.model.Attach;
import com.meixiaoliang.portal.modular.system.model.result.UploadResult;
import com.meixiaoliang.portal.modular.system.service.AttachService;

/**
 * 附件上传下载
 *
 * @author mei.xiaoliang@qq.com
 */
@RestController
@CrossOrigin
public class AttachController extends BaseController {

    @Value("${fileDir}")
    public String         FIRE_DIR;

    @Autowired
    private AttachService attachService;

    /**
     * 上传页面
     */
    @RequestMapping("/uploadPage")
    public ModelAndView uploadPage(ModelAndView mov) {
        mov.setViewName("uploadTest");
        return mov;
    }

    /**
     * 上传文件测试接口
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws IOException {

        // 文件上传
        String filePath = FileUtil.saveFile(file, FIRE_DIR);
        //        System.out.println("filePath: " + filePath);
        //        System.out.println("fileName: " + file.getOriginalFilename());
        //        System.out.println("fileSize: " + file.getSize());
        //        System.out.println("fileSubfix: " + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));

        // 附件信息落库
        Attach attach = new Attach();
        attach.setName(file.getOriginalFilename());
        attach.setUuid(UuidUtil.generate());
        attach.setPath(filePath);
        attach.setSize(file.getSize());
        attach.setSuffix(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)); // 这里加 1, 为了去除"."进入尾缀名
        //        System.out.println("suffix: " + attach.getSuffix());
        //        attach.setUserId(getUserSession().getId());
        attach.setUpdateTime(LocalDateTime.now());
        attachService.save(attach);

        String downloadUrl = DOWNLOAD_DIR + "/" + attach.getId() + "/" + attach.getUuid() + "/" + attach.getName();

        logger.info("附件真实路径: " + FIRE_DIR + filePath);
        logger.info("附件下载地址: " + downloadUrl);

        return ResponseUtil
            .buildSuccessResponse(new UploadResult().setId(attach.getId()).setUuid(attach.getUuid()).setName(attach.getName()).setDownloadUrl(downloadUrl));

    }

    /**
     * 下载
     */
    @RequestMapping("/download/{id}/{uuid}/{name}")
    public String download(HttpServletResponse response, @PathVariable Integer id, @PathVariable String uuid, @PathVariable String name) {

        QueryWrapper<Attach> queryWrapper = new QueryWrapper<Attach>().eq("id", id).eq("uuid", uuid);
        Attach attach = attachService.getOne(queryWrapper);
        AssertUtil.notNull(attach, "文件不存在");

        FileUtil.download(response, attach, FIRE_DIR);

        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 删除附件
     */
    @PostMapping("/delete/{id}/{uuid}/{name}")
    public String delete(@PathVariable Integer id, @PathVariable String uuid, @PathVariable String name) {

        // 查询附件 db 记录
        QueryWrapper<Attach> queryWrapper = new QueryWrapper<Attach>().eq("id", id).eq("uuid", uuid).eq("name", name);
        Attach attach = attachService.getOne(queryWrapper);
        // 删除记录
        AssertUtil.notNull(attach, "附件不存在或已删除");
        attachService.removeById(attach.getId());

        // TODO 删除文件

        return ResponseUtil.buildSuccessResponse();
    }

}
